'''
fuction : 客户端程序
author  : 辛天宇
date    : 2024-4-13
-------------------------------
author     date      modify
辛天宇   2024-4-15   结合GUI和网络通信

'''
import show
import tcp
import tool
import socket
import global_var


def send_handle(window, client_socket, values):
    global_var.TX_BUF = values['txbuff'] 
    print(f"txbuff={global_var.TX_BUF}")
    # 清理input
    window['txbuff'].update(value='')
    data = global_var.TX_BUF
    client_socket.sendall(data.encode())
    # 接收服务器的响应
    data = client_socket.recv(512)
    # 将字节字符串转化为字符串
    global_var.RX_BUF = data.decode('utf-8')
    # print(f"rx......{global_var.RX_BUF}") 

def quit_handel(client_socket):
    cmd='Q'
    client_socket.sendall(cmd.encode())
    tcp.disconnect_to_server(client_socket)

def motor_handel(window, client_socket, values):
    i = int(values['MOTOR_I'])
    global_var.MOTOR_DATA = str(abs(i)%360)
    if i >= 0:
        global_var.MOTOR_DIRECTION='0'
    else:
        global_var.MOTOR_DIRECTION='1'
    message = 's'+global_var.MOTOR_DIRECTION+global_var.MOTOR_DATA
    # 清理input
    window['MOTOR_I'].update(value='0')
    set_tx_buf('motor', message)
    send_cmd(client_socket)
    # 接收服务器的响应
    data = client_socket.recv(512)
    # 将字节字符串转化为字符串
    global_var.RX_BUF = data.decode('utf-8')
    # print(f"rx......{global_var.RX_BUF}") 

# 进行一次发送
def send_cmd(client_socket):
    data = global_var.TX_BUF
    client_socket.sendall(data.encode())
    # 接收服务器的响应
    data = client_socket.recv(512)
    # 将字节字符串转化为字符串
    global_var.RX_BUF = data.decode('utf-8')
    # print(f"rx......{global_var.RX_BUF}") 

# 设置发送消息
def set_tx_buf(device, message): 
    if device == 'sr04':
        global_var.TX_BUF = '@002'+message
    if device == 'led':
        global_var.TX_BUF = '@000'+message
    elif device == 'sr501':
        global_var.TX_BUF = '@001'+message
    elif device == 'irda':
        global_var.TX_BUF = '@003'+message
    elif device == 'motor':
        global_var.TX_BUF = '@004'+message
    elif device == 'dht11':
        global_var.TX_BUF = '@005'+message
    elif device == 'ds18b20':
        global_var.TX_BUF = '@006'+message
    elif device == 'AT24C02':
        global_var.TX_BUF = '@007'+message
    elif device == 'dac':
        global_var.TX_BUF = '@008'+message

# 解析IRDA传入的数据
def irda_data_analysis(cmd):
    if cmd[5] == 'r':
        global_var.IRDA_DATA = "RED"
    elif cmd[5] == 'm':
        global_var.IRDA_DATA = "MENU"
    elif cmd[5] == 't':
        global_var.IRDA_DATA = "TEST"
    elif cmd[5] == '+':
        global_var.IRDA_DATA = "+"
    elif cmd[5] == 'b':
        global_var.IRDA_DATA = "BACK"
    elif cmd[5] == 'l':
        global_var.IRDA_DATA = "LEFT"
    elif cmd[5] == 'p':
        global_var.IRDA_DATA = "START"
    elif cmd[5] == 'r':
        global_var.IRDA_DATA = "RIGHT"
    elif cmd[5] == '0':
        global_var.IRDA_DATA = "0"
    elif cmd[5] == '1':
        global_var.IRDA_DATA = "1"
    elif cmd[5] == '2':
        global_var.IRDA_DATA = "2"
    elif cmd[5] == '-':
        global_var.IRDA_DATA = "-"
    elif cmd[5] == 'c':
        global_var.IRDA_DATA = "c"
    elif cmd[5] == '3':
        global_var.IRDA_DATA = "3"
    elif cmd[5] == '4':
        global_var.IRDA_DATA = "4"
    elif cmd[5] == '5':
        global_var.IRDA_DATA = "5"
    elif cmd[5] == '6':
        global_var.IRDA_DATA = "6"
    elif cmd[5] == '7':
        global_var.IRDA_DATA = "7"
    elif cmd[5] == '8':
        global_var.IRDA_DATA = "8"
    elif cmd[5] == '9':
        global_var.IRDA_DATA = "9"

# 处理数据
def cmd_handle(window):
    cmd = global_var.RX_BUF
    global_var.RX_BUF="#000"
    if len(cmd) < 4:
        print("cmd ERROR")
        return -1
    if '@' == cmd[0]:
        # 目前驱动设备数量只有两位数
        if cmd[1] == '0':
            # LED: @000+1位命令位+1位数据位
            if cmd[2] == '0' and cmd[3] == '0':
                if cmd[5] == '1':
                    print("LED Status change success")
                elif cmd[5] == '0':
                    print("LED Status change failure")
                else:
                    print("message ERROR")
            # SR501:@001+1位数据位
            elif cmd[2] == '0' and cmd[3] == '1':
                if cmd[5] == '1':
                    print("有人")
                    message='有人'
                    window['SR501_O'].update(message)
                elif cmd[5] == '0':
                    print("无人")
                    message='无人'
                    window['SR501_O'].update(message)
                else:
                    print("message ERROR")
            # SR04
            elif cmd[2] == '0' and cmd[3] == '2':
                if cmd[4] == 'g':
                    global_var.SR04_DATA = cmd[5:8]
                    message = f"{global_var.SR04_DATA}cm"
                    window['SR04_O'].update(message)
                else:
                    print("SR04: message ERROR")               
            # irda
            elif cmd[2] == '0' and cmd[3] == '3':
                # message = cmd[5]
                # print(message)
                if cmd[4] == 'g':
                    irda_data_analysis(cmd)
                    window['IRDA_O'].update(global_var.IRDA_DATA)
            # motor
            elif cmd[2] == '0' and cmd[3] == '4':
                if cmd[4] == 's':
                    print("MOTOR: message SCUESS") 
                else:
                    print("MOTOR: message ERROR")  
            # dht11
            elif cmd[2] == '0' and cmd[3] == '5':
                if cmd[4] == 'g':
                    try:
                        global_var.TEM=cmd[5]+cmd[6]
                        global_var.HUM=cmd[7]+cmd[8]
                        message = f"{global_var.TEM}°C   {global_var.HUM}%"
                        window['DHT11_O'].update(message)
                    except:
                        message = "ERROR"
                        window['DHT11_O'].update(message)
                        print("DHT11: message ERROR")
                else:
                    message = "ERROR"
                    window['DHT11_O'].update(message)
                    print("DHT11: message ERROR")  
            # ds18b20
            elif cmd[2] == '0' and cmd[3] == '6':
                if cmd[4] == 'g':
                    try:
                        global_var.TEM=cmd[5]+cmd[6]
                        message = f"{global_var.TEM}°C"
                        window['DS18B20_O'].update(message)
                    except:
                        message = "ERROR"
                        window['DS18B20_O'].update(message)
                        print("DS18B20: message ERROR")
                else:
                    message = "ERROR"
                    window['DS18B20_O'].update(message)
                    print("DS18B20: message ERROR")
            # AT24C02
            elif cmd[2] == '0' and cmd[3] == '7':
                if cmd[4] == 'g':
                    try:
                        message = cmd[5:]
                        window['AT24C02_O'].update(message)
                    except:
                        message = "ERROR"
                        window['AT24C02_O'].update(message)
                        print("AT24C02: message ERROR")
                elif cmd[4] == 'p':
                    window['AT24C02_I'].update(value='')
                    print("AT24C02: write SUCCESS")
                else:
                    message = "ERROR"
                    window['AT24C02_O'].update(message)
                    print("AT24C02: message ERROR")
            # DAC&&spi
            elif cmd[2] == '0' and cmd[3] == '8':
                if cmd[4] == 'p':
                    print("DAC: SUCCESS")
                else:
                    print("DAC: message ERROR")

# 处理事件
def event_handle(window, client_socket):
    led = 0
    # 事件循环
    while True:  
        try:
            cmd_handle(window)
            event, values = window.read()
            if event == 'input':
                window['txbuff'].update(disabled=not values['input'])
            elif event == 'send':
                send_handle(window, client_socket, values)
            elif event == 'Clean':
                window['Output'].update(value='')
                window['AT24C02_O'].update(value='')
            elif event == 'dht11':
                window['DHT11_O'].update(value=' ')
                set_tx_buf('dht11', 'g')
                send_cmd(client_socket)
            elif event == 'ds18b20':
                window['DS18B20_O'].update(value=' ')
                set_tx_buf('ds18b20', 'g')
                send_cmd(client_socket)
            elif event == 'Quit': 
                quit_handel(client_socket) 
                print(f"See you.............")
                break
            elif event is None:
                print(f"xxxxxxxxxxxxxxxxxxxx")
                break
            elif event == 'LED':
                if led % 2 == 0:
                    set_tx_buf('led','p1')
                else:
                    set_tx_buf('led','p0')
                led+=1
                if led > 100:
                    led = 0
                send_cmd(client_socket)
            elif event == 'SR501':
                set_tx_buf('sr501','g')
                send_cmd(client_socket)
            elif event == 'SR04':
                set_tx_buf('sr04','g')
                send_cmd(client_socket)
            elif event == 'IRDA':
                set_tx_buf('irda','g')
                send_cmd(client_socket)
            elif event == 'MOTOR':
                motor_handel(window, client_socket, values)
            elif event == 'AT24C02_R':
                window['AT24C02_O'].update(value='')
                set_tx_buf('AT24C02','g')
                send_cmd(client_socket)
            elif event == 'AT24C02_W':
                global_var.AT24C02_DATA = values['AT24C02_I']
                set_tx_buf('AT24C02','p'+global_var.AT24C02_DATA)
                print(global_var.TX_BUF)
                window['AT24C02_I'].update(value='')
                send_cmd(client_socket)
            elif event == 'DAC':
                global_var.DAC_DATA = str(int(values['DAC']))
                print(global_var.DAC_DATA)
                set_tx_buf('dac','p'+global_var.DAC_DATA)
                send_cmd(client_socket)
            # 处理其他事件...
        except Exception as e:
            window.close()
            print(f"An error occurred: {e}")
            return 0
    window.close()
    return 0  

def main():
    # 创建GUI对象
    window = show.show_window('DefaultNoMoreNagging')
    # 尝试连接到服务器  
    client_socket = tcp.connect_to_server()
    if client_socket is not None: 
        event_handle(window, client_socket)

if __name__ == '__main__':
    main()
